<template>
  <StartLayout>
    <h2 class="title">用户登录</h2>
    <p class="subtitle">让配送更简单，让生意更轻松</p>
    <!-- 登录方式切换 -->
    <div class="login-tabs">
      <div class="tab-item" :class="{ active: loginType === 'sms' }" @click="switchLoginType('sms')">
        手机验证码登录
      </div>
      <div class="tab-item" :class="{ active: loginType === 'password' }" @click="switchLoginType('password')">
        账号密码登录
      </div>
    </div>

    <transition name="fade" mode="out-in">
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form" @keyup.enter="handleLogin">
        <!-- 手机验证码登录 -->
        <template v-if="loginType === 'sms'">
          <el-form-item prop="phone">
            <el-input v-model="loginForm.phone" placeholder="请输入手机号" size="large" clearable class="custom-input">
              <template #prefix>
                <i class="el-icon-mobile" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="smsCode">
            <div class="sms-code-wrapper">
              <el-input v-model="loginForm.smsCode" placeholder="短信验证码" size="large"
                class="sms-code-input custom-input">
                <template #prefix>
                  <i class="el-icon-message" />
                </template>
              </el-input>
              <el-button :disabled="smsCodeDisabled" :loading="smsCodeLoading" class="sms-code-button"
                @click="sendSmsCode">
                {{ smsCodeText }}
              </el-button>
            </div>
          </el-form-item>
        </template>

        <!-- 账号密码登录 -->
        <template v-else>
          <el-form-item prop="account">
            <el-input v-model="loginForm.account" placeholder="邮箱/手机号" size="large" clearable class="custom-input">
              <template #prefix>
                <i class="el-icon-user" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="密码" size="large" show-password
              class="custom-input">
              <template #prefix>
                <i class="el-icon-lock" />
              </template>
            </el-input>
          </el-form-item>
        </template>

        <div class="form-options">
          <el-checkbox v-model="rememberMe" size="small">
            记住我
          </el-checkbox>
          <el-link type="primary" :underline="false" size="small" @click="gotoReset">
            忘记密码?
          </el-link>
        </div>

        <el-form-item>
          <Button :loading="loading" @click="handleLogin">登录</Button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="login-footer">
      <span>还没有账号？</span>
      <el-link type="primary" :underline="false" @click="goToRegister">立即注册</el-link>
    </div>
  </StartLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import '@/styles/pages/auth/login.scss'
import { showCaptcha } from '@/utils/captcha'
import Button from '@/components/ui/Button.vue'
import type { AccoutLogin, PhoneLogin } from '@/types'
import { accountLogin, phoneCode, phoneLogin } from '@/services/api/merchant'
import StartLayout from '@/components/layout/MainLayout.vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 登录表单引用
const loginFormRef = ref<FormInstance>()

// 登录状态
const loading = ref(false)
const rememberMe = ref(false)
const loginType = ref<'password' | 'sms'>('password') // 默认改为手机验证码登录

// 验证码
const smsCodeDisabled = ref(false)
const smsCodeLoading = ref(false)
const smsCodeCountdown = ref(0)

// 登录表单数据
const loginForm = reactive({
  account: '15798661220',
  password: '123456',
  phone: '',
  smsCode: '',
})


// 更新表单验证规则
const loginRules = computed<FormRules>(() => {
  if (loginType.value === 'sms') {
    return {
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      smsCode: [
        { required: true, message: '请输入短信验证码', trigger: 'blur' }
      ]
    }
  } else {
    return {
      account: [{ validator: validateAccount, trigger: 'blur' }],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    }
  }
})

const validateAccount = (_rule: any, value: any, callback: any) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (value === '') {
    callback(new Error('请输入邮箱或手机号'))
    return
  }

  // 检查是否符合手机号或邮箱格式
  if (!phoneRegex.test(value) && !emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱或手机号'))
    return
  }
  callback()
}



// 短信验证码按钮文字
const smsCodeText = computed(() => {
  if (smsCodeLoading.value) return '发送中...'
  if (smsCodeCountdown.value > 0) return `${smsCodeCountdown.value}秒后重发`
  return '获取验证码'
})

// 切换登录方式
const switchLoginType = (type: 'password' | 'sms') => {
  loginType.value = type
  // 清空表单验证
  loginFormRef.value?.clearValidate()
}

// 发送短信验证码
const sendSmsCode = () => {
  if (!loginForm.phone) {
    ElMessage.error('请输入手机号')
    return
  }

  if (!/^1[3-9]\d{9}$/.test(loginForm.phone)) {
    ElMessage.error('请输入正确的手机号')
    return
  }

  smsCodeLoading.value = true

  // 模拟发送短信验证码
  setTimeout(async () => {
    smsCodeLoading.value = false
    smsCodeDisabled.value = true
    smsCodeCountdown.value = 60

    // 倒计时
    const timer = setInterval(() => {
      smsCodeCountdown.value--
      if (smsCodeCountdown.value <= 0) {
        clearInterval(timer)
        smsCodeDisabled.value = false
      }
    }, 1000)
    const res = await phoneCode(loginForm.phone)
    if (res.code === 200) {
      ElMessage.success('验证码已发送，请注意查收')
    }
  }, 1000)
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      const isValid = await showCaptcha()
      console.log(isValid);

      if (isValid.success) {
        if (loginType.value === 'sms') {
          // 手机验证码登录
          const phoneLoginForm: PhoneLogin = {
            phone: loginForm.phone,
            code: loginForm.smsCode,
          }
          const res = await phoneLogin(phoneLoginForm)
          if (res.code === 200) {
            loading.value = true
            localStorage.setItem('token', res.data)
          }

        } else {
          const accountLoginForm: AccoutLogin = {
            account: loginForm.account,
            password: loginForm.password,
          }
          // 账号密码登录
          const res = await accountLogin(accountLoginForm)
          if (res.code === 200) {
            loading.value = true
            localStorage.setItem('token', res.data)
            router.push('/home')
          }
        }
      }
    } else {
      ElMessage.error('请填写正确的登录信息')
    }
  })
}

const gotoReset = () => {
  router.push({ name: 'resetInfo' })
}

const goToRegister = () => {
  router.push({ name: 'register' })
}

</script>

<style lang="scss" scoped></style>